const md5 = require("md5")
const { loginDao } = require("../dao/adminDao")
const jwt = require("jsonwebtoken")
const { ValidationError } = require("../utils/errors")
const { updateAdminDao } = require("../dao/adminDao")
const { formatResponse } = require("../utils/tool")

//登录时候的业务层
module.exports.loginService = async function(loginInfo){
    try {
        const { remember } = loginInfo
        // loginInfo.loginPwd = md5(loginInfo.loginPwd)
        let data = await loginDao(loginInfo)
        if(data && data.dataValues){
            let loginPeriod = null
            // 这里加token
            data = data.dataValues
            const {id,loginId,name} = data
            loginPeriod = remember?+remember:1
            const token = jwt.sign({
                id,
                loginId,
                name
            },md5(process.env.JWT_SECRET),{
                expiresIn: 60*60*24*loginPeriod
            })
            return {
                token,
                data
            }
        }  
        return { data }
    } catch (error) {
        console.log(error,'error');
    }

}

module.exports.updateAdminService = async function(accountInfo){
      accountInfo.loginPwd = md5(accountInfo.loginPwd)
      const data = await loginDao(accountInfo)
      if(data&&data.dataValues){
        const { loginPwd,name,loginId,newLoginPwd } = accountInfo
        const newPassword = md5(newLoginPwd)
        await updateAdminDao({
            loginPwd:newPassword,
            name,
            loginId
        })
        return formatResponse(0,"",{
            ...accountInfo
        })
      }else{
        throw new ValidationError("旧密码不正确")
      }
}